<?php
namespace app\common\middleware;
use app\common\library\JwtUtil;
use think\facade\Request;
use Closure;
use app\admin\model\Admin;
class JwtAuth
{
    public function handle($request, Closure $next)
    {	

 		// 或者直接从请求对象获取
	    $url = $request->pathinfo();
	    $noneed_login = ['Login/index','login/wxlogin','Complaint/sub','Device/weighLatest','common/clickCaptcha','common/checkClickCaptcha','Complaint/lists','Complaint/reply','Complaint/details','Hardwaresms/receive','Hardwaresms/start'];  //不用校验的路径
        $token = $request->header('Authorization') ?? '';
        $access_token = $request->header('AccessToken') ?? '';
        if (!empty($access_token)) {
            $admin = Admin::where("access_token",$access_token)->field("id")->find();
            $request->adminId = $admin->id;
        }
        if(in_array($url,$noneed_login)){
             return $next($request);
        }

        if (empty($token)) {
            return json(['code' => 401, 'msg' => 'Token 缺失']);
        }
 


        // 验证 Token
        $payload = JwtUtil::validateToken($token);
        if (!$payload) {
            return json(['code' => 401, 'msg' => 'Token 无效或已过期']);
        }

        // 将用户ID存入请求上下文
        $request->userId = $payload['user_id'];
        return $next($request);
    }
}